package com.cowain.monitor.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cowain.monitor.dao.PmsEhrContentLogDao;
import com.cowain.monitor.dao.PmsSysUserDao;
import com.cowain.monitor.datasources.DataSourceNames;
import com.cowain.monitor.datasources.annotation.DataSource;
import com.cowain.monitor.entity.EhrStaffEntity;
import com.cowain.monitor.entity.PmsSysDeptEntity;
import com.cowain.monitor.entity.PmsSysUserEntity;
import com.cowain.monitor.service.PmsSysUserService;
import com.cowain.monitor.utils.JsonUtils;
import com.cowain.monitor.utils.PmsConstantUtils;
import com.cowain.monitor.utils.PmsProjectUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *  
 *  * @author 冬暖
 *  * @projectName pms-monitor
 *  * @title     PmsSysUserServiceImpl   
 *  * @package    com.cowain.monitor.service.impl  
 *  * @description    用户信息       
 *  * @date   2020/8/11 9:29  
 *  * @version V1.0.0
 *  
 */
@Service
public class PmsSysUserServiceImpl extends ServiceImpl<PmsSysUserDao, PmsSysUserEntity> implements PmsSysUserService {
    @Autowired
    private PmsEhrContentLogDao ehrContentLogDao;
    @Autowired
    private PmsProjectUtil pmsProjectUtil;

    /**
     * 获取上一次结束时间
     * @return 开始时间
     */
    @Override
    @DataSource(name = DataSourceNames.FIRST)
    public Date findDate(){
        return ehrContentLogDao.findStartTime(PmsConstantUtils.EHR_USER,new Date());
    }
    /**
     * 获取用户信息
     * @return 用户信息
     */
    @Override
    @DataSource(name = DataSourceNames.SECOND)
    public List<PmsSysUserEntity> findUser(Date start){
        List<PmsSysUserEntity> pmsSysUserEntityList = new ArrayList<>();
        String s = pmsProjectUtil.updateTime(pmsProjectUtil.getUserUrl(), start);
        List<EhrStaffEntity> ehrStaffEntities = JsonUtils.parseArray(s,"list", EhrStaffEntity.class);
        if(ehrStaffEntities.size() > 0){
            for (EhrStaffEntity ehrStaffEntity : ehrStaffEntities) {
                PmsSysUserEntity sysUserEntity = new PmsSysUserEntity();
                sysUserEntity.setUserId(ehrStaffEntity.getStId() == null ? null : ehrStaffEntity.getStId().longValue());
                sysUserEntity.setNameZh(ehrStaffEntity.getNameZh());
                sysUserEntity.setUsername(ehrStaffEntity.getHrId());
                //sha256加密
                String salt = RandomStringUtils.randomAlphanumeric(20);
                sysUserEntity.setPassword("123456");
                sysUserEntity.setPassword(new Sha256Hash(sysUserEntity.getPassword(), salt).toHex());
                sysUserEntity.setSalt(salt);
                Integer sex = pmsProjectUtil.findSex(ehrStaffEntity.getSex());
                sysUserEntity.setGender(sex);
                sysUserEntity.setEmail(ehrStaffEntity.getMail());
                sysUserEntity.setMobile(ehrStaffEntity.getMobile());
                sysUserEntity.setStatus(0);
                String creatorId = ehrStaffEntity.getCreatorId();
                EhrStaffEntity ehrStaffEntity1;
                Optional<EhrStaffEntity> first = ehrStaffEntities.stream().filter(item -> item.getHrId() != null && ehrStaffEntity.getCreatorId() != null && item.getHrId().equals(creatorId)).findFirst();
                ehrStaffEntity1 = first.orElseGet(EhrStaffEntity::new);
                if(ehrStaffEntity1.getStId() == null){
                    sysUserEntity.setCreateUserId(null);
                }else {
                    sysUserEntity.setCreateUserId(ehrStaffEntity1.getStId().longValue());
                }
                sysUserEntity.setCreateTime(ehrStaffEntity.getCreateTime() == null ? new Date() : ehrStaffEntity.getCreateTime());
                sysUserEntity.setDeptId(ehrStaffEntity.getStDept() == null ? null :ehrStaffEntity.getStDept().longValue());
                sysUserEntity.setInsertTime(new Date());
                sysUserEntity.setPosition(StringUtils.isBlank(ehrStaffEntity.getStPositionName()) ? "null" : ehrStaffEntity.getStPositionName());
                sysUserEntity.setHrId(ehrStaffEntity.getHrId());
                sysUserEntity.setIsDel(0);
                sysUserEntity.setWork(8);
                sysUserEntity.setIsAdmin(PmsConstantUtils.IS_NOT_ADMIN);
                sysUserEntity.setIsDel(0);
                sysUserEntity.setIsRed(0);
                pmsSysUserEntityList.add(sysUserEntity);
            }
            List<PmsSysUserEntity> insert = new ArrayList<>();
            List<PmsSysUserEntity> update = new ArrayList<>();
            pmsSysUserEntityList.forEach(user -> {
                PmsSysUserEntity sysUserEntity = baseMapper.findUserById(user.getUserId(),user.getUsername());
                if(sysUserEntity != null){
                    sysUserEntity.setIsRed(0);
                    update.add(user);
                }else {
                    insert.add(user);
                }
            });
            if (insert.size() > 0){
                List<List<PmsSysUserEntity>> split = pmsProjectUtil.split(insert, 12);
                split.forEach(user -> baseMapper.insertEhrUser(user));
            }
            if(update.size() > 0){
                baseMapper.deletUser(update);
                List<List<PmsSysUserEntity>> splits = pmsProjectUtil.split(update, 12);
                splits.forEach(dept ->
                        baseMapper.insertEhrUser(dept)
                );
            }
        }else {
            System.out.println("暂未有数据同步");
        }
        return baseMapper.findUser(PmsConstantUtils.IS_DEL);
    }
    /**
     * 用户信息
     */
    @Override
    @DataSource(name = DataSourceNames.FIRST)
    public void insertUser(List<PmsSysUserEntity> list){
        List<PmsSysUserEntity> insertUser = new ArrayList<>();
        List<PmsSysUserEntity> updateUser = new ArrayList<>();
        List<PmsSysUserEntity> romveUser = new ArrayList<>();
        list.forEach(user -> {
            PmsSysUserEntity sysUserEntity = null;
            try {
                sysUserEntity = baseMapper.findUserId(user.getUserId(),user.getUsername());
            } catch (Exception e) {
                System.out.println("e = " + user.getUserId() +"---"+user.getUsername());
                e.printStackTrace();
            }
            if(sysUserEntity != null){
                romveUser.add(sysUserEntity);
                updateUser.add(user);
            }else {
                insertUser.add(user);
            }
        });
        List<PmsSysUserEntity> list1 = new ArrayList<>();
        boolean flag = false;
        List<String> lists = pmsProjectUtil.addUserList(insertUser, list1);
        if(insertUser.size() > 0 && lists.size() > 0){
            List<PmsSysUserEntity> list2 = new ArrayList<>();
            insertUser.forEach(info -> {
                if(info.getUsername() == null){
                    list2.add(info);
                }
            });
            insertUser.removeAll(list2);
            if(insertUser.size() > 0){
                List<List<PmsSysUserEntity>> split = pmsProjectUtil.split(insertUser, 12);
                for (List<PmsSysUserEntity> clientEntities : split) {
                    baseMapper.insertUser(clientEntities);
                }
                flag = true;
            }
        }
        if(updateUser.size() > 0){
            if(list1.size() > 0){
                updateUser.addAll(list1);
            }
            if(romveUser.size() > 0){
                baseMapper.deleteUserByIds(romveUser);
            }
            List<List<PmsSysUserEntity>> split = pmsProjectUtil.split(updateUser, 12);
            for (List<PmsSysUserEntity> pmsClientEntities : split) {
                baseMapper.insertUser(pmsClientEntities);
            }
        }
        if(list1.size() ==0){
            list1.addAll(updateUser);
        }
        if(lists.size() > 0 || list1.size() > 0) {
            List<PmsSysUserEntity> pmsClientEntities = new ArrayList<>();
            if(flag){
                pmsClientEntities.addAll(insertUser);
            }
            pmsProjectUtil.addEhrLog(pmsClientEntities, updateUser, PmsConstantUtils.EHR_USER, PmsConstantUtils.EHR_USER,new Date());
        }
    }

    /**
     * 修改用户信息
     */
    @Override
    @DataSource(name = DataSourceNames.SECOND)
    public void updateUser(List<PmsSysUserEntity> list){
        list.forEach(so -> {
            if(so.getUsername() == null || StringUtils.isBlank(so.getUsername())){
                so.setIsRed(0);
            }else {
                so.setIsRed(1);
            }
        });
        List<PmsSysUserEntity> collect = list.stream()
                .filter(s -> s.getIsRed() == 1)
                .collect(Collectors.toList());
        List<List<PmsSysUserEntity>> split = pmsProjectUtil.split(collect, 12);
        for (List<PmsSysUserEntity> customerEntities : split) {
            baseMapper.updateUsers(customerEntities);
        }
    }
}
